﻿module Sustainalytics.ValidationRules.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class ValidationRulesBackendService {


        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private $location: ng.ILocationService;
        private $upload: any;
        private $filter: ng.IFilterProvider;

        constructor(
            $q: ng.IQService,
            $http: ng.IHttpService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            $location: ng.ILocationService,
            $upload,
            $filter: ng.IFilterProvider) {

            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjectsAdmin = staticObjectsAdmin;
            this.$upload = $upload;
            this.$location = $location;
            this.$filter = $filter;
        }
        
        public uploadWhiteListFile(file: File, progress: number): ng.IPromise<{}> {

            progress = 0;
            var ctx = this;
            var def = ctx.$q.defer();

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: "POST",
                    url: ctx.validationRulesUrl(),
                    headers: { 'Content-Disposition': 'attachment; filename="' + file.name + '"', 'Content-Type': file.type, },
                    data: reader.result
                })
                    .progress(evt => { progress = (100.0 * evt.loaded / evt.total); })
                    .success((data) => { def.resolve(data); })
                    .error((data) => { def.resolve(data) });

            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }
        
        private validationRulesUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() +
                "/companyserv/api/v1/validationrulesfiles";
        }
    }

    var mod = angular.module(validationRulesAdminModuleName);

    mod.service('ValidationRulesBackendService',
        ['$q', '$http', 'notificationFactory', 'staticObjectsAdmin', '$location', '$upload', '$filter', ValidationRulesBackendService]);
}